package com.xhui.reggie.service.impl;

//import com.alicp.jetcache.Cache;
//import com.alicp.jetcache.anno.CreateCache;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhui.reggie.entity.User;
import com.xhui.reggie.mapper.UserMapper;
import com.xhui.reggie.service.UserService;
import com.xhui.reggie.utils.SMSUtils;
import com.xhui.reggie.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * Author XHui
 * Date 2023/1/19 9:55
 * Version 1.0
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    /*@CreateCache(name = "reggie_validateCode", expire = 5, timeUnit = TimeUnit.MINUTES)
    private Cache<String, String> validateCodeCache;*/

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     * @param user 前端信息
     * @return 是否成功
     */
    @Override
    public boolean sendMsg(User user) {
        // 获取手机号
        String phone = user.getPhone();
        if (StringUtils.isNotBlank(phone)){
            // 生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            // 调用工具类SmsUtils中的API -> 发送验证码给手机号
            // SMSUtils.sendMessage("瑞吉外卖", "", phone, code);

            // 发送成功之后，把验证码存储到缓存中，且该验证码应该5分钟内有效
            // validateCodeCache.put(phone, code);
            ValueOperations opsForValue = redisTemplate.opsForValue();
            opsForValue.set(phone, code, 5, TimeUnit.MINUTES);
            return true;
        }
        // 手机号为空白的，返回false
        return false;
    }

    @Override
    public boolean checkValidateCode(String phone, String code) {
//        String cachedCode = validateCodeCache.get(phone);
        ValueOperations opsForValue = redisTemplate.opsForValue();
        String cachedCode = (String) opsForValue.get(phone);
        // 比较前端传递过来的验证码和缓存中的验证码是否一致
        boolean flag = Objects.equals(cachedCode, code);

        if (flag) {
            // 比对成功
            // 删除缓存的验证码
            redisTemplate.delete(phone);
        }
        return flag;
    }
}
